﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Data;
using LitJson;

public static class Convertjson
{
    public static T GetModel<T>(string Json) where T : new()
    {
        try
        {
            return LitJson.JsonMapper.ToObject<T>(Json);
        }
        catch { } 
        return default(T);
    }
    public static string ToJson(object obj)
    {
        return LitJson.JsonMapper.ToJson(obj);
    }

    /// <summary>
    /// T类型的model List转成DataTable
    /// </summary>
    /// <param name="Tlis"></param>
    /// <returns></returns>
    public static DataTable ConvertListToDT<T>(List<T> Tlis)
    {
        if (Tlis == null || Tlis.Count < 1)
        {
            return null;
        }
        // 定义dt
        DataTable dtret = new DataTable();
        // 获得此模型的类型
        Type type = typeof(T);
        // 获得此模型的公共属性
        PropertyInfo[] propertys = type.GetProperties();
        foreach (PropertyInfo pi in propertys)
        {
            dtret.Columns.Add(pi.Name);
        }
        foreach (T t in Tlis)
        {
            DataRow dr = dtret.NewRow();
            foreach (PropertyInfo pi in propertys)
            {
                // 检查DataTable是否包含此列
                if (dtret.Columns.Contains(pi.Name))
                {
                    if (pi.GetValue(t, null) == null || pi.GetValue(t, null).ToString() == new DateTime().ToString())
                    {
                        dr[pi.Name] = DBNull.Value;
                    }
                    else
                    {
                        dr[pi.Name] = pi.GetValue(t, null);
                    }
                }
            }
            dtret.Rows.Add(dr);
        }
        dtret.AcceptChanges();
        return dtret;
    }

   
}

